// AdminWrongQuestionController.java
package com.scuec.groupfive.Controller;

import com.scuec.groupfive.service.AdminWrongQuestionService;
import com.scuec.groupfive.vo.AdminWrongQuestionDetailVO;
import com.scuec.groupfive.vo.AdminWrongQuestionOverviewVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/wrong-questions")
public class AdminWrongQuestionController {

    private static final Logger logger = LoggerFactory.getLogger(AdminWrongQuestionController.class);

    @Autowired
    private AdminWrongQuestionService wrongQuestionService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/search-user")
    public Map<String, Object> searchUser(@RequestParam String username) {
        String sql = "SELECT user_id as userId, username FROM users WHERE username = ? AND role = 'student' LIMIT 1";
        try {
            return jdbcTemplate.queryForMap(sql, username);
        } catch (Exception e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在");
        }
    }

    @GetMapping("/overview")
    public Map<String, Object> getWrongQuestionOverview(
            @RequestParam Long userId,
            @RequestParam(required = false) Integer subjectId,
            @RequestParam(required = false) String startDateStr,
            @RequestParam(required = false) String endDateStr,
            @RequestParam(required = false, defaultValue = "0") Integer page,
            @RequestParam(required = false, defaultValue = "5") Integer size,
            @RequestParam(required = false, defaultValue = "time") String sort
    ) {
        // 输出日志以验证参数
        logger.info("接收到的参数: userId={}, subjectId={}, startDateStr={}, endDateStr={}, page={}, size={}, sort={}",
                userId, subjectId, startDateStr, endDateStr, page, size, sort);

        // 日期处理
        Date startDate = null;
        Date endDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        try {
            if (startDateStr != null && !startDateStr.isEmpty()) {
                // 将起始日期转换为该月的第一天
                startDate = sdf.parse(startDateStr + "-01");
            }
            if (endDateStr != null && !endDateStr.isEmpty()) {
                // 将结束日期转换为该月的最后一天
                java.util.Calendar cal = java.util.Calendar.getInstance();
                cal.setTime(sdf.parse(endDateStr + "-01"));
                cal.set(java.util.Calendar.DAY_OF_MONTH, cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH));
                endDate = cal.getTime();
            }
        } catch (ParseException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "日期格式错误，请使用yyyy-MM格式");
        }

        // 添加日志确认传递给服务层的日期参数
        logger.info("传递给服务层的日期参数: startDate={}, endDate={}", startDate, endDate);

        // 获取总数量
        long total = wrongQuestionService.countWrongQuestions(userId, subjectId, startDate, endDate);

        // 获取分页数据
        List<AdminWrongQuestionOverviewVO> list = wrongQuestionService.getWrongQuestionOverview(
                userId, subjectId, startDate, endDate, page, size, sort);

        // 返回分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("total", total);
        return result;
    }

    @GetMapping("/detail/{questionId}")
    public AdminWrongQuestionDetailVO getWrongQuestionDetail(
            @RequestParam Long userId,
            @PathVariable String questionId) {
        logger.info("获取错题详情: userId={}, questionId={}", userId, questionId);
        try {
            AdminWrongQuestionDetailVO detail = wrongQuestionService.getWrongQuestionDetail(userId, questionId);
            logger.info("获取到的错题详情: {}", detail);
            if (detail == null) {
                throw new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到错题详情");
            }
            return detail;
        } catch (Exception e) {
            logger.error("获取错题详情出错, userId: " + userId + ", questionId: " + questionId, e);
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "获取错题详情失败", e);
        }
    }

    @GetMapping("/count")
    public Map<String, Long> countWrongQuestions(
            @RequestParam Long userId,
            @RequestParam(required = false) Integer subjectId,
            @RequestParam(required = false) String startDateStr,
            @RequestParam(required = false) String endDateStr
    ) {
        Date startDate = null;
        Date endDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        try {
            if (startDateStr != null && !startDateStr.isEmpty()) {
                startDate = sdf.parse(startDateStr + "-01");
            }
            if (endDateStr != null && !endDateStr.isEmpty()) {
                java.util.Calendar cal = java.util.Calendar.getInstance();
                cal.setTime(sdf.parse(endDateStr + "-01"));
                cal.set(java.util.Calendar.DAY_OF_MONTH, cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH));
                endDate = cal.getTime();
            }
        } catch (ParseException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "日期格式错误，请使用yyyy-MM格式");
        }

        long total = wrongQuestionService.countWrongQuestions(userId, subjectId, startDate, endDate);
        return Collections.singletonMap("total", total);
    }
}